<?php

namespace app\pay\command;

use IEXBase\TronAPI\Providers\HttpProvider;
use IEXBase\TronAPI\Tron;
use think\cache\driver\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use Etherscan\Client;

class CheckErc extends Command
{
    protected function configure()
    {
        $this->setName('CheckErc')
            ->setDescription('erc');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/
        $api_key = "9D2UQSMVU9UWRBGPY58SQERAC83AW9JPY5";
        $client = new Client($api_key);
        //获取erc充值订单
        $list = Db::name("recharge")
            ->field("id,member_id,usdt,pay_hash")
            ->where(["delete_time" => 0, "type" => 1, "status" => 0])
            ->select()->toArray();
        $data = [];
        foreach ($list as $k => $v) {
            $info = $client->api("proxy")->getTransactionByHash($v['pay_hash']);
            if (isset($info['result'])) {
                $res = $this->saveData($info['result'], $v);
                if ($res) $data[$k] = $v['id'];
            }
        }
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('结束:' . implode(",", $data));
    }

    /**
     * Notes:更新充值订单并上分
     * User:
     * DateTime: 2022-01-16 10:36
     * @param $info
     * @param $order
     * @return int|string
     */
    public function saveData($info, $order)
    {
        $res = 0;
        if (isset($info['input'])) {
            $redis = new Redis();
            $site_info = json_decode($redis->get("site_info"), true);
            if (!$site_info) $site_info = cmf_get_option('site_info');
            $to = '0x' . strtolower(substr($info['input'], 34, 40));
            if ($to == strtolower($site_info['erc_usdt'])) {
                try {
                    Db::startTrans();
                    $usdt = hexdec(substr($info['input'], -16)) / 1000000;
                    $member = Db::name("member")->field("usdt")->where(["id" => $order['member_id']])->find();
                    $data['usdt'] = $usdt;
                    $data['from_address'] = $info['from'];
                    $data['status'] = 1;
                    $data['update_time'] = time();
                    $res = Db::name("recharge")->where(['id' => $order['id']])->save($data);
                    $usdt += $member['usdt'];
                    if ($res) Db::name("member")->where(["id" => $order['member_id']])->save(["usdt" => $usdt]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        }
        return $res;
    }

}
